package cn.ybz21.hibot.util.shell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CmdExec {
//	public static void main(String args[]) {
////		 System.out.println(new CmdExec().execCmd4Str(" ls -l "));
//		System.out.println(new CmdExec().execCmd4Str(" rosnode list "));
//	}

	/**
	 * 
	 * @param cmd
	 * @return
	 */
	public String execCmd4Str(String cmd) {
		String result = "";
		try {
			String[] cmds = new String[] { "/bin/sh", "-c", cmd };
			Process ps = Runtime.getRuntime().exec(cmds);

			BufferedReader br = new BufferedReader(new InputStreamReader(
					ps.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
			}
			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 * @param cmd
	 * @return
	 */
	public List<String> execCmd4List(String cmd) {
		List<String> strs = new ArrayList<String>();
		try {
			String[] cmds = new String[] { "/bin/sh", "-c", cmd };
			Process ps = Runtime.getRuntime().exec(cmds);

			BufferedReader br = new BufferedReader(new InputStreamReader(
					ps.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line).append("\n");
				strs.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strs;
	}
}